package common

import (
	"backend/config"
	"fmt"
	"log"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var DB *gorm.DB

// InitDB initializes the database connection with the given configuration.
func InitDB() (*gorm.DB, error) {
	args := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=true",
		config.Configs.Database.Username,
		config.Configs.Database.Password,
		config.Configs.Database.Host,
		config.Configs.Database.Port,
		config.Configs.Database.Database,
		config.Configs.Database.Charset)

	//log.Print(args)

	db, err := gorm.Open(config.Configs.Database.DriverName, args)
	if err != nil {
		log.Printf("failed to connect to database: %v", err)
		return nil, err
	}

	// Set up connection pool settings
	db.DB().SetMaxOpenConns(100)
	db.DB().SetMaxIdleConns(10)
	db.DB().SetConnMaxLifetime(time.Hour)

	// Enable logging (optional)
	db.LogMode(true)

	// Assign the global DB variable
	DB = db

	return db, nil
}

// GetDB returns the initialized database instance.
func GetDB() *gorm.DB {
	if DB == nil {
		log.Fatal("Database not initialized")
	}
	return DB
}

func CloseDB() error {
	if DB != nil {
		return DB.Close()
	}
	return nil
}
